import axios from 'axios';
axios.defaults.timeout = 100000;
axios.defaults.baseURL = 'api';
/**
 * http request 拦截器
 */
axios.interceptors.request.use(
    (config) => {
        let token = window.localStorage.getItem('my-login-token');
        config.headers.Token = token || '';
        return config;
    },
    (error) => {
        console.log("请求出错：", error);
    }
);
/**
 * http response 拦截器
 */
axios.interceptors.response.use(
    (response) => {
        if (response && response.data && response.data.code === 401) {
            // 未登录或者登录失效
            window.reactHistory.push("/login");
        }
        return response;
    },
    (error) => {
        console.log("请求出错：", error);
    }
);

// get post请求封装
export function get(url, param) {
    return new Promise((resolve, reject) => {
        axios.get(url, { params: param }).then(response => {
            resolve(response ? response.data : {});
        }, err => {
            reject(err)
        }).catch((error) => {
            reject(error)
        })
    })
}

export function post(url, data) {
    return new Promise((resolve, reject) => {
        axios.post(url, data).then(response => {
            resolve(response ? response.data : {});
        }, err => {
            reject(err);
        }).catch((error) => {
            reject(error)
        })
    })
}

export function formPost(url, data) {
    return new Promise((resolve, reject) => {
        axios.post(url, data, {
            'headers': {
                'Content-Type': 'multipart/form-data'
            }
        }).then(response => {
            resolve(response ? response.data : {});
        }, err => {
            reject(err);
        }).catch((error) => {
            reject(error)
        })
    })
}